package com.uphone.kingmall.activity.personal;

import android.os.Handler;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.PayAliCallbackBean;
import com.uphone.kingmall.bean.PayResult;
import com.uphone.kingmall.bean.PayWxCallbackBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.AppUtil;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.HttpParamsUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.view.SubmitButton0;
import com.uphone.kingmall.wxapi.WXPayEntryActivity;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : 王雨
 *     e-mail :
 *     time   : 2018/07/31
 *     desc   :余额充值
 *     version: 1.0
 * </pre>
 */
public class RechargeActivity extends BaseActivity {
    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.et_recharge)
    EditText etRecharge;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.rb_wchat)
    RadioButton rbWchat;
    @BindView(R.id.rb_union)
    RadioButton rbUnion;
    @BindView(R.id.rg_pay)
    RadioGroup rgPay;
    @BindView(R.id.btn_submit)
    SubmitButton0 btnSubmit;
    @BindView(R.id.ll)
    LinearLayout ll;


    public static final int TYPE_INTEGRAL = 0X0011;// 金币充值
    public static final int TYPE_WALLET = 0X0022;// 佣金明细
    @IntentData
    int type = TYPE_WALLET;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_recharge_balance;
    }

    @Override
    public void initView() {
        btnSubmit.setRelaViews(etRecharge);
        setStatusBar();
        String title = "充值";
        switch (type) {
            case TYPE_INTEGRAL:
                title = "金币充值";
                break;
            case TYPE_WALLET:
                title = "余额充值";
                break;
        }
        CommonUtil.initTitle(this, title, ll);

        rgPay.check(R.id.rb_ali);
    }

    @Override
    public void initData() {

    }

    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        if (CommonUtil.checkViewEmpty("请输入充值金额", etRecharge)) {
            return;
        }

        String rechargeType = "";
        switch (type) {
            case TYPE_INTEGRAL:
                rechargeType = "20";
                break;
            case TYPE_WALLET:
                rechargeType = "10";
                break;
        }
        HttpParams params = HttpParamsUtils.getInstance()
                .put("money", etRecharge.getText().toString().trim())
                .put("rechargeType", rechargeType)
                .put("payType", rgPay.getCheckedRadioButtonId() == R.id.rb_ali ? "1" : "2")
                .getParams();//	1支付宝；2微信

        OkGoUtils.progressRequest(MyUrl.recharge, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    if (rgPay.getCheckedRadioButtonId() == R.id.rb_ali) {
                        //支付宝支付
                        alipay(body);
                    } else if (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat) {
                        // 微信支付
                        wxPay(body);
                    } else {
                        // 佣金支付
                        paySuccess();
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void wxPay(final String body) {
        AppUtil.checkWchat(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayWxCallbackBean bean = GsonUtils.getGson().fromJson(body, PayWxCallbackBean.class);
                PayWxCallbackBean.SignBean sign = bean.getSign();
                PayReq request = new PayReq();
                request.appId = sign.getAppId();
                request.partnerId = sign.getPartnerId();
                request.prepayId = sign.getPrepayId();
                request.packageValue = sign.getPackageValue();
                request.nonceStr = sign.getNonceStr();
                request.timeStamp = sign.getTimeStamp();
                request.sign = sign.getSign();
                WXPayEntryActivity.activity = RechargeActivity.this;
                MyApplication.api.sendReq(request);
            }
        });

    }

    @Override
    public void wxPaySuccess() {
        super.wxPaySuccess();
        paySuccess();
    }

    private void alipay(final String body) {
        AppUtil.checkAli(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayAliCallbackBean bean = GsonUtils.getGson().fromJson(body, PayAliCallbackBean.class);
                final String sign = bean.getSign();
                // 必须异步调用
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(RechargeActivity.this);
                        final Map<String, String> resultMap = alipay.payV2(sign, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                PayResult result = new PayResult(resultMap);
                                String resultStatus = result.getResultStatus();
                                if (TextUtils.equals(resultStatus, "9000")) {
                                    LogUtils.e("handleMessage: 已经支付成功，支付成功");
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付成功");
                                    paySuccess();
                                } else if (TextUtils.equals(resultStatus, "6001")) {
                                    LogUtils.e("handleMessage: 已经取消支付");
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付取消");
                                } else {
                                    LogUtils.e("handleMessage: 未知状态");
                                    com.blankj.utilcode.util.ToastUtils.showShort(resultStatus);
                                }
                            }
                        });
                    }
                }).start();
            }
        });

    }

    private void paySuccess() {
        ToastUtils.showShortToast(RechargeActivity.this, "充值成功！");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                KeyboardUtils.hideSoftInput(RechargeActivity.this);
                finish();
            }
        }, 500);
    }
}
